package com.xyy.ec.qualification.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.xyy.ec.qualification.pojo.DataSourceConfig;
import com.xyy.ec.qualification.pojo.SellerDataConfig;
import com.xyy.ec.qualification.utils.DBUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author jiangxing
 */
@Component
@Slf4j
@DependsOn("sellerDataConfig")
public class ConfigManagerService {
    private static final Logger logger = LoggerFactory.getLogger(ConfigManagerService.class);
    private static final Object datasourceLock = new Object();
    private static volatile DruidDataSource druidDataSource;
    private static volatile DataSourceConfig dataSourceConfig;

    @PostConstruct
    public void initDataSourceAfterSpringInit() {
        initDatasource();

        if (Objects.isNull(druidDataSource) || Objects.isNull(dataSourceConfig)) {
            logger.info("ybmForErpSetup初始化数据源失败了，请稍后一分钟。");
            CompletableFuture.supplyAsync(() -> {
                for (int i = 0; i < 5; i++) {
                    initDatasource();
                    if (Objects.nonNull(druidDataSource) && Objects.nonNull(dataSourceConfig)) {
                        logger.info("ybmForErpSetup第{}次初始化数据源成功了。。。", i + 1);
                        return null;
                    }
                    logger.info("ybmForErpSetup第{}次初始化数据源失败了，请稍后一分钟。", i + 1);

                    try {
                        TimeUnit.MINUTES.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                logger.info("ybmForErpSetup初始化数据源失败了，请检查数据库连接配置是否有误！");
                return null;
            });
        } else {
            logger.info("ybmForErpSetup初始化数据源成功了。。。");
        }
    }

    @Value("${h.api.host}")
    private String hApiHost;


    private static void initDatasource() {
        DataSourceConfig dsc = new DataSourceConfig();
        try {
            dsc.setHost(SellerDataConfig.host);
            dsc.setPort(SellerDataConfig.port);
            dsc.setBdType(SellerDataConfig.dbType);
            dsc.setUserName(SellerDataConfig.userName);
            dsc.setUserPass(SellerDataConfig.userPass);
            dsc.setDbName(SellerDataConfig.dbName);
            init(dsc, DBUtil.init(dsc, true));

        } catch (Exception e) {
            logger.info("setUp", e);
        }
    }

    public static void init(DataSourceConfig dsc, DruidDataSource ds) {
        synchronized (datasourceLock) {
            if (null != ds) {
                if (null != druidDataSource) {
                    try {
                        druidDataSource.close();
                    } catch (Exception e) {
                        logger.info("init_close连接池失败_dsc={}", JSON.toJSONString(dsc));
                    }
                }
                druidDataSource = ds;
                dataSourceConfig = dsc;
            }
        }
    }

    public static DataSourceConfig getDatasourceConfig() {
        return dataSourceConfig;
    }

    public static DruidDataSource getDataSource() {
        synchronized (datasourceLock) {
            return druidDataSource;
        }
    }

    public DataSourceConfig getDataSourceConfig() {
        return dataSourceConfig;
    }
}
